﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RWLib
{
    /// <summary>
    /// Klauzula - alternatywa literałów logicznych
    /// Przykład:
    /// 1. ~p lub q lub y
    /// </summary>
    public class Clause :  ICloneable
    {

        private List<Fluent> conditionsOR;

        public Clause(List<Fluent> conditionsOr) {
            conditionsOR = conditionsOr;
        }

        public int Count {
            get { return conditionsOR.Count(); }
        }

        public List<Fluent> Conditions {
            get { return conditionsOR; }
        }

        public override string ToString()
        {
            var sb = new StringBuilder();
            for (int i = 0; i < conditionsOR.Count()-1; ++i )
            {
                sb.Append(conditionsOR[i].ToString());
                sb.Append(" or ");
            }
            sb.Append(conditionsOR.Last().ToString());
            return sb.ToString();
        }

        public bool Eval(List<Fluent> fluents) {
            var value = conditionsOR.Exists(condition => condition.Eval(fluents.Get(condition)));
            return value;
        }

        public bool Eval() {
            return conditionsOR.Exists(condition => condition.Eval());
        }

        public bool Conflict(Clause clause) {
            foreach (var cond in conditionsOR) {
                try
                {
                    if (clause.Conditions.Get(cond) != null && clause.Conditions.Get(cond).Conflicts(cond))
                    {
                        return true;
                    }
                }
                catch (FluentNotFoundException ex) { 
                }
            }
            return false;
        }

        public object Clone()
        {
            return new Clause(conditionsOR);
        }
        
    }
}
